<template>
	<z-paging-swiper class="page">
		<CustomNavBar class="navbar fixed-top" title="我的收藏">
			<template v-slot:left><uni-icons type="left" size="20" @click="goBack"></uni-icons></template>
		</CustomNavBar>
		<z-tabs ref="tabs1" :list="tabsList" :current="currentIndex" @change="changeTab" scroll-count="0"
			:active-style="{fontWeight: '600',fontSize: '36rpx',color: '#333333'}"
			:inactive-style="{fontWeight: '400',fontSize: '28rpx',color: '#666666'}">
		</z-tabs>

		<swiper class="swiper" :current="currentIndex" @change="onChange">
			<swiper-item class="swiper-item" v-for="(item, index) in tabsList" :key="item.id || index">
				<!-- 用户选项卡 -->
				<template v-if="item.id === 'USER'">
					<findPeopleItem ref="peopleItem" :tabIndex="index" :currentId="currentId"
						:currentIndex="currentIndex" :serviceTabs="item.children" :browseType="currentId" />
				</template>

				<!-- 优派 -->
				<template v-if="item.id === 'VIEW_SONIC'">
					<PersonalFavoritesItem ref="viewSonicRef" :tabIndex="index" :currentId="currentId"
						:currentIndex="currentIndex" :serviceTabs="item.children" :browseType="currentId" />
				</template>

				<!-- 信息 -->
				<template v-if="item.id === 'INFO'">
					<partTimeJobItem ref="partTimeJobItemRef" :tabIndex="index" :currentId="currentId"
						:currentIndex="currentIndex" :serviceTabs="item.children" :browseType="currentId" />
				</template>

				<!-- 找活 -->
				<template v-if="item.id === 'NEAR'">
					<findJobItem ref="findJobItemRef" :tabIndex="index" :currentId="currentId"
						:currentIndex="currentIndex" :serviceTabs="item.children" :browseType="currentId" />
				</template>
			</swiper-item>
		</swiper>
	</z-paging-swiper>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		toRefs,
		nextTick
	} from 'vue';
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import PersonalFavoritesItem from './Service/PersonalFavoritesItem.vue';
	import findPeopleItem from './User/findPeopleItem.vue';
	import partTimeJobItem from './partTimeJob/partTimeJobItem.vue';
	import findJobItem from './FindJob/findJobItem.vue';
	import {
		collectCategoryApi
	} from "@/api/personalFavorites.js";

	const state = reactive({
		tabsList: [],
		currentIndex: 0,
		currentId: '',
		isCategoryLoaded: false // 标记分类数据是否加载完成
	});
	const {
		tabsList,
		currentIndex,
		currentId,
		isCategoryLoaded
	} = toRefs(state);

	// 组件引用
	const peopleItem = ref(null);
	const viewSonicRef = ref(null);
	const partTimeJobItemRef = ref(null);
	const findJobItemRef = ref(null);

	const fetchCategoryData = async () => {
		try {
			const res = await collectCategoryApi();
			if (res && res.code === 200 && res.data) {
				const data = res.data;
				const newTabsList = [];
				for (const key in data) {
					newTabsList.push({
						id: key,
						name: data[key],
						...(key === 'JOB' || key === 'PART_TIME_JOB' ? {
							children: []
						} : {})
					});
				}
				state.tabsList = newTabsList;
				if (state.tabsList.length > 0) {
					currentIndex.value = 0;
					currentId.value = state.tabsList[0].id;
				}
				state.isCategoryLoaded = true; // 标记分类数据加载完成
			}
		} catch (error) {
			console.error('获取分类数据失败:', error);
			state.tabsList = [];
			state.isCategoryLoaded = true; // 即使失败也标记为已加载（避免一直等待）
		}
	};

	onLoad(() => {
		fetchCategoryData();
	});

	let isChangingTab = false; // 防止重复切换

	const changeTab = async (index) => {
		if (isChangingTab || currentIndex.value === index) return;
		isChangingTab = true;
		try {
			currentIndex.value = index;
			currentId.value = tabsList.value[index].id;
			await nextTick();
			// reloadCurrentList();
		} finally {
			isChangingTab = false;
		}
	};

	const onChange = async (e) => {
		if (isChangingTab) return;
		isChangingTab = true;
		try {
			const newIndex = e.detail.current;
			if (currentIndex.value === newIndex) return;
			currentIndex.value = newIndex;
			currentId.value = tabsList.value[newIndex].id;
			await nextTick();
			// reloadCurrentList();
		} finally {
			isChangingTab = false;
		}
	};

	const reloadCurrentList = async () => {
		// 仅在分类数据加载完成后才触发子组件刷新
		if (!isCategoryLoaded.value) return;
		await nextTick();
		switch (currentId.value) {
			case 'USER':
				peopleItem.value?.reload?.();
				break;
			case 'VIEW_SONIC':
				viewSonicRef.value?.reload?.();
				break;
			case 'INFO':
				partTimeJobItemRef.value?.reload?.();
				break;
			case 'NEAR':
				findJobItemRef.value?.reload?.();
				break;
			default:
				break;
		}
	};

	defineExpose({
		reloadCurrentList
	});
	const goBack=(()=>{
		uni.navigateBack();
	})
</script>

<style lang="scss" scoped>
	.page {
		position: relative;
		height: 100vh;
		box-sizing: border-box;
		overflow: hidden;

		.swiper {
			height: calc(100vh - 80rpx);
			background-color: #f5f5f5;
			overflow: hidden;
		}

		.swiper-item {
			height: 100%;
		}

		::v-deep .z-tabs-list {
			width: 100% !important;
			justify-content: space-evenly !important;
		}
	}
</style>